<template>
  <div class="ageReformApply-info">
    <el-scrollbar height="calc( 100vh - 150px)">
      <div style="padding: 10px 0 20px">
        <el-card class="box-card" shadow="always" style="background: #fafafa">
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>基本信息</span>
            </div>
          </template>
          <el-row style="padding: 10px 40px">
            <el-col :span="8">
              <span>老人姓名:</span><span style="margin-left: 10px">{{
                basicInfo.name
              }}
            </span></el-col>
            <el-col :span="8"><span style="display: inline-block; width: 68px; text-align: right">性别:</span><span style="margin-left: 10px">{{
                sys_user_sex.find((item) => item.value == basicInfo.sex)
                  ? sys_user_sex.find((item) => item.value == basicInfo.sex)
                      .label
                  : ""
              }}</span></el-col>
            <el-col :span="8"
              ><span
                style="display: inline-block; width: 68px; text-align: right"
                >年龄:</span
              ><span style="margin-left: 10px">{{
                basicInfo.age
              }}</span></el-col
            >
            <el-col :span="24" style="margin-top: 30px">
              <span>家庭住址:</span
              ><span style="margin-left: 10px">{{
                basicInfo.address
              }}</span></el-col
            >
          </el-row>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 15px"
        >
          <template #header>
            <div
              class="card-header"
              style="
                padding-bottom: 4px;
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <span>适老化改造产品</span>
              <el-button
                type="primary"
                size="small"
                plain
                @click="addTableData"
                v-if="showStatus !== '2'"
                >新增</el-button
              >
            </div>
          </template>
          <div>
            <div>
              <span>合计金额：</span><span>{{ total }}元</span>
            </div>
            <div style="margin-top: 10px">
              <el-table
                v-loading="loading"
                :data="evaluationCriteriaList"
                stripe
                border
                max-height="250"
              >
                <el-table-column
                  label="序号"
                  type="index"
                  width="80"
                  align="center"
                />
                <el-table-column label="产品名称" align="center" prop="name" />
                <el-table-column
                  label="单价（元）"
                  align="center"
                  prop="unitPrice"
                />
                <el-table-column label="数量" align="center" prop="number"/>
                <el-table-column
                  label="总价（元）"
                  align="center"
                  prop="totalPrice"
                />
                <el-table-column label="设备编号" align="center" prop="imei" />
                <el-table-column
                  label="施工单位"
                  align="center"
                  prop="constructionUnit"
                />
                <el-table-column
                  label="安装人员"
                  align="center"
                  prop="constructionPersonnel"
                />
                <el-table-column
                  label="施工日期"
                  align="center"
                  prop="constructionDate"
                />
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <span v-if="showStatus == '2'">
                      <el-button link type="primary" @click="info(scope.row)">查看</el-button>
                    </span>
                    <span v-else>
                      <el-button link type="primary" @click="edit(scope.row)">编辑</el-button>
                      <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card image-view-container"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="showStatus != '2'"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>改造前照片</span>
            </div>
          </template>
          <div>
            <div style="margin-top: 10px">
              <el-upload
                list-type="picture-card"
                :limit=fileLimit
                :action="url"
                :file-list="beforeElderlyRemodelGalleryList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :headers="upload.headers"
                :before-upload="beforeUpload"
                :on-success="handleAvatarSuccess"
                :on-exceed="handleExceed"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <el-dialog
                v-model="dialogVisible"
                class="image-view"
                :width="dialogImageWidth + 'px'"
              >
                <img
                  class="w-full"
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  @load="adjustDialogWidth"
                />
              </el-dialog>
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="showStatus != '2'"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>改造后照片</span>
            </div>
          </template>
          <div style="margin-top: 10px">
            <el-upload
              multiple
              list-type="picture-card"
              :action="url"
              :limit=fileLimit
              :file-list="afterElderlyRemodelGalleryList"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleAfterRemove"
              :headers="upload.headers"
              :before-upload="beforeUpload"
              :on-success="handleAvatarAfterSuccess"
              :on-exceed="handleExceed"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog
              v-model="dialogVisible"
              class="image-view"
              :width="dialogImageWidth + 'px'"
            >
              <img
                class="w-full"
                :src="dialogImageUrl"
                alt="Preview Image"
                @load="adjustDialogWidth"
              />
            </el-dialog>
          </div>
        </el-card>

        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="showStatus == '2'"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>改造前照片</span>
            </div>
          </template>
          <div class="demo-image">
            <div
              v-for="(fit, index) in beforeElderlyRemodelGalleryList"
              :key="index"
              style="display: inline-block; margin-left: 20px"
            >
              <el-image
                multiple
                :limit="1"
                style="width: 200px; height: 200px"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[fit.imgUrl]"
                :src="fit.imgUrl"
              />
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="showStatus == '2'"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>改造后照片</span>
            </div>
          </template>
          <div class="demo-image">
            <div
              v-for="(fit, index) in afterElderlyRemodelGalleryList"
              :key="index"
              style="display: inline-block; margin-left: 20px"
            >
              <el-image
                style="width: 200px; height: 200px"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[fit.imgUrl]"
                :src="fit.imgUrl"
              />
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          v-if="checkAcceptElderlyRemodelGalleryList.length > 0"
          style="background: #fafafa; margin-top: 20px"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>验收照片</span>
            </div>
          </template>
          <div class="demo-image">
            <div
              v-for="(item, index) in checkAcceptElderlyRemodelGalleryList"
              :key="index"
              style="display: inline-block; margin-left: 20px"
            >
              <el-image
                style="width: 200px; height: 200px"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[item.imgUrl]"
                :src="item.imgUrl"
              />
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="checkAcceptForm.checkAcceptResult"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>验收结果</span>
            </div>
          </template>
          <div>
            <el-form
              ref="checkAcceptformRef"
              :model="checkAcceptForm"
              :rules="rules"
              label-width="90px"
            >
              <el-form-item label="验收结论" prop="checkAcceptResult">
                <el-radio-group v-model="checkAcceptForm.checkAcceptResult">
                  <el-radio
                    :disabled="true"
                    v-for="(item, index) in acceptance_result"
                    :key="index"
                    :label="item.value"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="checkAcceptForm.checkAcceptNotes"
                  :disabled="true"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 8 }"
                  placeholder="请输入备注"
                  show-word-limit
                  maxlength="500"
                />
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 15px"
        >
          <div style="text-align: right; padding-right: 50px">
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="submitFormDebounceHandler('0')"
              v-if="showStatus === '0'"
              >确 定</el-button
            >
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="submitFormDebounceHandler('1')"
              v-if="showStatus == '1'"
              >提 交</el-button
            >
            <el-button @click="goCancel" v-if="showStatus == '2'"
              >返 回</el-button
            >
            <el-button @click="goCancel" v-else>取 消</el-button>
          </div>
        </el-card>

        <el-dialog
          v-model="open"
          :title="title"
          append-to-body
          width="800px"
          v-if="open"
          @close="cancel"
          :close-on-click-modal="false"
        >
          <prodect-form
            @closed="cancel"
            :homeBedApplyId="basicInfo.id"
            :formatDate="formatDate"
            :flag="disAbledFlag"
          ></prodect-form>
        </el-dialog>
      </div>
    </el-scrollbar>
  </div>
</template>

<style scoped lang="scss">
.ageReformApply-info {
  padding: 20px;
}
</style>
<script setup name="ageReformApply">
import { onMounted } from "vue";
import { debounce } from "@/utils/debounce.js";
const { proxy } = getCurrentInstance();
const { sys_user_sex, acceptance_result } = proxy.useDict(
  "sys_user_sex",
  "acceptance_result",
);
import { useRouter, useRoute } from "vue-router";
import {
  elderlyOrientedRemodelInfo,
  elderlyOrientedRemodelProductDel,
  productList,
  elderlyOrientedRemodelSave,
} from "@/api/AgeAppropriate";
import { getToken } from "@/utils/auth";
import prodectForm from "./project_form.vue";
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const open = ref(false);
const disAbledFlag = ref(false);
const title = ref("新增适老化改造产品");
const dialogVisible = ref(false);
const dialogImageUrl = ref("");
const disabled = ref(false);
const status = ref("0");
const total = ref(0);
const dialogImageWidth = ref("0");
const url = ref(
  process.env.VUE_APP_BASE_API + "/file/upload/pk-elderly-remodel",
);
const fileLimit = ref(10);
const beforeElderlyRemodelGalleryList = ref([]);
const afterElderlyRemodelGalleryList = ref([]);
const checkAcceptElderlyRemodelGalleryList = ref([]);
const evaluationCriteriaList = ref([]);
const showStatus = ref("0");
const upload = reactive({
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
});

const data = reactive({
  form: {},
  basicInfo: {},
  formatDate: {},
  rules: {
    checkAcceptResult: [
      { required: true, message: "请选择验收结论", trigger: "change" },
    ],
  },
  ageReformItem: {},
  checkAcceptForm: {},
});
const { form, rules, basicInfo, formatDate, checkAcceptForm } = toRefs(data);

function cancel(data) {
  if (data) {
    getProductList(basicInfo.value.id);
  }
  open.value = false;
  formatDate.value = {};
  disAbledFlag.value = false;
}

/** 提交按钮 */
const submitFormDebounceHandler = debounce((data) => submitForm(data), 500);
function submitForm(data) {
  if (beforeElderlyRemodelGalleryList.value.length <= 0) {
    proxy.$modal.msgError("改造前照片不能为空");
    return false;
  }
  if (afterElderlyRemodelGalleryList.value.length <= 0) {
    proxy.$modal.msgError("改造后照片不能为空");
    return false;
  }
  let obj = {
    id: basicInfo.value.id,
    remodelStatus: data,
    beforeElderlyRemodelGalleryList: beforeElderlyRemodelGalleryList.value,
    afterElderlyRemodelGalleryList: afterElderlyRemodelGalleryList.value,
  };
  elderlyOrientedRemodelSave(obj).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    router.push("/elderlyReform/ageReform");
  });
  console.log("obj", obj);
}
function beforeUpload(file) {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    proxy.$modal.msgError("请上传正确的图片格式");
  }
  // 校验图片格式是否合法
  const isLegal =
      file.type === 'image/jpeg' ||
      file.type === 'image/jpg' ||
      file.type === 'image/png';
  // 文件大小不超过2MB
  const isLt1M = file.size / 1024 / 1024 < 1;

  if (!isLegal) {
    // 文件格式是否合法
    proxy.$modal.msgError("上传头像图片只能是 JPG、JPEG、PNG 格式!");
  }

  if (!isLt1M) {
    // 图片大小超过2MB
    proxy.$modal.msgError("上传头像图片大小不能超过1MB!");
  }

  return isImage && isLegal && isLt1M;
}

function handleExceed(files, fileList) {

proxy.$modal.msgError(`当前限制选择` + fileLimit.value + `个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);

}

function adjustDialogWidth() {
  // Get the width of the image when it is loaded
  const imgElement = document.querySelector(".image-view img");
  if (imgElement) {
    dialogImageWidth.value = imgElement.width;
  }
}

function handleAvatarSuccess(response, file) {
  if (response.code == 200) {
    let obj = {
      name: response.data.name,
      imgUrl: response.data.url,
      type: "0",
    };
    beforeElderlyRemodelGalleryList.value.push(obj);
  } else {
    proxy.$modal.msgError("图片上传错误");
  }
}
function handleAvatarAfterSuccess(response, file) {
  if (response.code == 200) {
    let obj = {
      name: response.data.name,
      imgUrl: response.data.url,
      type: "1",
    };
    afterElderlyRemodelGalleryList.value.push(obj);
  } else {
    proxy.$modal.msgError("图片上传错误");
  }
}
function handlePictureCardPreview(file) {
  console.log(file);
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}
function edit(row) {
  formatDate.value = row;
  formatDate.value.typeId = row.typeId - 0;
  title.value = "编辑适老化改造产品";
  open.value = true;
}
function info(row) {
  formatDate.value = row;
  formatDate.value.typeId = row.typeId - 0;
  title.value = "查看适老化改造产品";
  disAbledFlag.value = true;
  open.value = true;
}
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      return elderlyOrientedRemodelProductDel([row.id]);
    })
    .then(() => {
      getProductList(basicInfo.value.id);
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
function handleRemove(file, fileList) {
  let arr = [];
  for (let i of fileList) {
    console.log(i);
    if (i.response) {
      arr.push({
        name: i.response.data.name,
        imgUrl: i.response.data.url,
        type: "0",
        url: i.response.data.url,
      });
    } else {
      arr.push({
        name: i.name,
        imgUrl: i.imgUrl,
        type: "0",
        url: i.imgUrl,
      });
    }
  }

  beforeElderlyRemodelGalleryList.value = arr;
}
function handleAfterRemove(file, fileList) {
  let arr = [];
  for (let i of fileList) {
    console.log(i);
    if (i.response) {
      arr.push({
        name: i.response.data.name,
        imgUrl: i.response.data.url,
        type: "0",
        url: i.response.data.url,
      });
    } else {
      arr.push({
        name: i.name,
        imgUrl: i.imgUrl,
        type: "0",
        url: i.imgUrl,
      });
    }
  }
  afterElderlyRemodelGalleryList.value = arr;
}
function addTableData() {
  open.value = true;
}
function goCancel() {
  router.go(-1);
}

function getProductList(id) {
  productList(id).then((res) => {
    evaluationCriteriaList.value = res.productInfo.productList;
    total.value = res.productInfo.totalPrice;
  });
}

onMounted(() => {});
function getInfo(id) {
  elderlyOrientedRemodelInfo(id).then((res) => {
    console.log("res=====", res);
    basicInfo.value.name = res.elderlyOrientedInfo.applyName;
    basicInfo.value.age = res.elderlyOrientedInfo.age;
    basicInfo.value.sex = res.elderlyOrientedInfo.sex;
    basicInfo.value.address = res.elderlyOrientedInfo.address;
    basicInfo.value.id = res.elderlyOrientedInfo.id;

    checkAcceptForm.value.checkAcceptResult = res.elderlyOrientedInfo.checkAcceptResult;
    checkAcceptForm.value.checkAcceptNotes = res.elderlyOrientedInfo.checkAcceptNotes;

    if (res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList.length > 0) {
      for (let i in res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList) {
        if (res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList[i].imgUrl) {
          res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList[i].url =
            res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList[i].imgUrl;
          beforeElderlyRemodelGalleryList.value =
            res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList;
        }
      }
    }
    if (res.elderlyOrientedInfo.afterElderlyRemodelGalleryList.length > 0) {
      for (let i in res.elderlyOrientedInfo.afterElderlyRemodelGalleryList) {
        if (res.elderlyOrientedInfo.afterElderlyRemodelGalleryList[i].imgUrl) {
          res.elderlyOrientedInfo.afterElderlyRemodelGalleryList[i].url =
            res.elderlyOrientedInfo.afterElderlyRemodelGalleryList[i].imgUrl;
          afterElderlyRemodelGalleryList.value =
            res.elderlyOrientedInfo.afterElderlyRemodelGalleryList;
        }
      }
    }
    if (
      res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList.length > 0
    ) {
      for (let i in res.elderlyOrientedInfo
        .checkAcceptElderlyRemodelGalleryList) {
        if (
          res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList[i].imgUrl
        ) {
          res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList[i].url =
            res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList[
              i
            ].imgUrl;
          checkAcceptElderlyRemodelGalleryList.value =
            res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList;
        }
      }
    }
  });
}
const stopWatch = watch(
  () => route,
  (newVal, oldVal) => {
    status.value = newVal.params.status;
    showStatus.value = newVal.params.showStatus;
    getInfo(newVal.params.id);
    getProductList(newVal.params.id);
  },
  { immediate: true },
);

onBeforeUnmount(() => {
  stopWatch();
});
</script>
<style scoped lang="scss">
:deep(.el-card.is-always-shadow .el-dialog:not(.is-fullscreen)) {
  width: 100%;
}
:deep(.el-card.is-always-shadow .el-dialog:not(.is-fullscreen) img) {
  width: 100%;
}
</style>
